var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
let mph = require('../../utils/util.js');
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min.js");

Page({
  data: {
    sousuoT: [],
    city: '',
    res: 0,
    resnum: 0,
    btn_hide_blien: null,
    panduan_time_show: true,
    modalName: null,
    couponlist: [],
    list: null,
    cart_list:{},//购物车列表
    temp_val: {home8_sel:0},
    arrLsit: [],
    arrnum: 0,
    buildUrl: [
      { key: 'keyword', url: '/pages/product_list/product_list?keyword=' },
      { key: 'special', url: '/pages/special/special?special_id=' },
      { key: 'goods', url: '/pages/product_detail/product_detail?goods_id=' },
      { key: 'goodsxxx', url: '/pages/product_detail/product_detail?goods_id=' },
      { key: 'class', url: '/pages/classification/classification?gc_id=' },
    ],//页面跳转,轮播页面

  },
  scroll(e) {
  },
  //index.php?act=other_member&op=get_cart
  get_cart_num() {//购物车做比较用的
    let that = this;
    let k = wx.getStorageSync('key');
    wx.request({
      url: ApiUrl + "index.php?act=other_member&op=get_cart",
      data: { act: 'other_member', op: 'get_cart', key: k },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        if (result.data.code == 200) {
          //获取购物车数组
          let tval = that.data.temp_val;
          tval.cart_list = result.data.datas
          that.setData({
            temp_val: tval
          })
          //end
          if (result.data.datas == []) {
            let arrJ = [];
            for (let name in result.data.datas) {
              let arrjson = {
                key: name,
                val: result.data.datas[name]
              }
              arrJ.push(arrjson);
            }

            let goodsDataarr = [];
            if (result.data.datas) {
              for (let i = 0; i < that.data.list.length; i++) {
                let goodsData = that.data.list[i];
                for (let name in goodsData) {
                  if (name == 'goods') {
                    goodsDataarr = goodsData[name].item;
                  }
                }
              }
            }

            for (let j = 0; j < goodsDataarr.length; j++) {
              for (let k = 0; k < arrJ.length; k++) {
                if (goodsDataarr[j].goods_id == arrJ[k].key) {
                  goodsDataarr[j].goods_num = arrJ[k].val;
                }
              }

            }
          } else {
            let arrJ = [];
            for (let name in result.data.datas) {
              let arrjson = {
                key: name,
                val: result.data.datas[name]
              }
              arrJ.push(arrjson);
            }

            let goodsDataarr = [];
            if (result.data.datas && that.data.list) {
              for (let i = 0; i < that.data.list.length; i++) {
                let goodsData = that.data.list[i];
                for (let name in goodsData) {
                  if (name == 'goods') {
                    goodsDataarr = goodsData[name].item;
                  }
                }
              }
            }

            for (let j = 0; j < goodsDataarr.length; j++) {
              goodsDataarr[j].goods_num = 0;
            }
          }
        } else {
        }


        that.setData({
          list: that.data.list
        });
      }
    })
  },
  changeGoodsNum(e) {
    let that = this;
    let goods_id = e.currentTarget.dataset.id;
    let item = e.currentTarget.dataset.item;
    let k = wx.getStorageSync('key');

    for (let i = 0; i < that.data.list.length; i++) {
      let goodsData = that.data.list[i];
      for (let name in goodsData) {
        if (name == 'goods') {
          let arr = goodsData[name].item;

          that.addshopping_num(arr)
          for (let j = 0; j < arr.length; j++) {
            if (arr[j].goods_id == goods_id) {
              // that.data.arrnum++;

              arr[j].goods_num++;

              that.addShoppingCart(k, goods_id, arr[j].goods_num);
            }

          }
        }
      }
    }
    that.setData({
      list: that.data.list
    });
  },
  /*** 购物车数量加减 */
  changeGoodsNum1:function(e){
    var that =this ;
    var tval = that.data.temp_val;
    let item = e.currentTarget.dataset.item;
    //新添加购物车数量
    if (tval.cart_list[item.goods_id] == undefined){
      tval.cart_list[item.goods_id] = 0;
    }
    //累加购物车
    let n = parseInt(tval.cart_list[item.goods_id]);
    var num = n + 1;
    tval.cart_list[item.goods_id] = num;

    //数据提交给后台
    let url = 'index.php?act=member_cart&op=type_add';
    mph.postRequest(url, { goods_id: item.goods_id, quantity: num },
      (res) => {
        if (res.data.code == 200) {
          //更新当前点击的商品数量
          that.setData({
            temp_val: tval
          })
          //底部导航购物车数量
          var s = mph.sum(tval.cart_list)
          item.goods_num = s
          that.addshopping_num([item])
        }
      })
  },
  addshopping_num(arr) {//购物车上左上角设置添加物品的个数！！！
    let that = this;
    that.data.res = 0;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].goods_num > 0) {
        that.data.res += arr[i].goods_num;
      }
    }
    that.data.resnum++;
    let total_limit_num = wx.getStorageSync('total_limit_num');
    if (that.data.res == 0) {
      wx.setTabBarBadge({//移除tabbar右上角的文本
        index: 3,	//tabbar下标
        text: '' + (total_limit_num + 1)	//显示的内容
      })
    } else {
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + (total_limit_num + that.data.resnum)	//显示的内容
      })
    };
    that.setData({
      res: that.data.res,
    })
  },
  addShoppingCart(k, id, num) {//购物车购买数量
    // key 当前登录令牌
    // goods_id 商品编号
    // quantity 购买数量
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=member_cart&op=type_add",
      data: { key: k, goods_id: id, quantity: num },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        if (result.statusCode == 200) {
          if (result.data.code == 200) {
          } else {
          }
        } else {
        }

      }
    })
  },
  onLoad: function (options) {
    this.share_tips();
    this.getcity();

    const app = getApp();

    var that = this;
    var key = app.globalData.key;
    wx.request({
      url: ApiUrl + 'index.php?act=index&op=special&special_id=3',
      data: {},
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var list = res.data.datas.list;
        

        let arr = [];
        for (let i = 0; i < list.length; i++) {
          let goodsData = list[i];
          for (let name in goodsData) {
            if (name == 'goods') {
              arr = goodsData[name].item;
            }
          }
        }
        for (let i = 0; i < arr.length; i++) {
          arr[i].goods_num = 0;
        }

        //多选框获取第一个元素,并默认选中
        var f = mph.getkey(list, 'home8')
        that.get_goods_list(f.item[0].data);

        that.setData({
          list: list,
        });

      },
      fail: function (res) {
      },
    });

    if (!key) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
      return false;
    }
  },
  searchMore: function () {
    wx.reLaunch({
      url: '/pages/search/search',
    })
  },
  buildUrl: function (type, data) {
    var WapSiteUrl = "";
    switch (type) {
      case 'keyword':
        return WapSiteUrl = '/pages/product_list/product_list?keyword=' + data;
      case 'special':
        return WapSiteUrl = '/pages/special/special?special_id=' + data;
      case 'goods':
        return WapSiteUrl = '/pages/product_detail/product_detail?goods_id=' + data;
      case 'goodsxxx':
        return WapSiteUrl = '/pages/product_detail/product_detail?goods_id=' + data;
      case 'url':
        return data;
    }
    return WapSiteUrl;

  },
  imageLoad: function (val) {
    var type = val.target.dataset.type;
    var imgH = val.detail.height;
    var imgW = val.detail.width;
    var screeW = wx.getSystemInfoSync().windowWidth;
    var screeR = screeW / imgW;
    var height = imgH * screeR + "px";
    var that = this;
    var v = that.data.temp_val;
    switch (type) {
      case "home1pic":
        v.home1H = height
        break;
      case "advPic":
        v.advPicH = height
       break;
    }
    that.setData({
      temp_val: v
    });

  },
  onReady() {
    var date = new Date();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    
    if (hour == 0 && minute == 0 && second == 0) {
      // if (hour != 0 && minute != 0 && second != 0) {
      wx.setStorageSync('btn_hide_blien', false);
    } else {
      let btn_hide_blien = wx.getStorageSync('btn_hide_blien');
      this.setData({
        btn_hide_blien: btn_hide_blien
      })

    }

    let user_info_ = wx.getStorageSync('userinfo')
    if (user_info_.user_type == "old") {
      this.addCoupon('');//老人
    } else {
      this.addCoupon('new');//新人
    }

    this.get_cart_num();
  },
  showModal() {
    var btn_hide_blien = wx.getStorageSync('btn_hide_blien');
    if (!btn_hide_blien) {
      this.setData({
        modalName: 'Image'
      })
    }
  },
  hideModal() {
    // this.addCoupon();
    this.setData({
      modalName: null
    })
  },
  panduan_time() {

    this.setData({
      btn_hide_blien: true
    })
  },
  addCoupon() {
    let that = this;
    var timestamp = Date.parse(new Date());
    var expiration = timestamp + 3600000*20; //一小时之后
    var data_expiration = wx.getStorageSync('data_expiration');
    if (timestamp <= data_expiration)return ;
    wx.setStorageSync('data_expiration', expiration);
    wx.request({
      url: ApiUrl + 'index.php?act=voucher&op=voucher_tpl_list',
      data: {
        act: 'voucher',
        op: 'voucher_tpl_list',
        recommend: 1,
        type: ''//new新人
      },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success(res) {
        let btn_hide_blien = wx.getStorageSync('btn_hide_blien');

        if (res.data.code == 200) {
          let data = res.data.datas.voucher_list;

          // this.couponlist = data;
          that.setData({
            couponlist: data
          })
          if (data.length == 0) {
            that.setData({
              btn_hide_blien: true
            })
          } else {
            that.showModal();
          }
        } else {
          that.setData({
            btn_hide_blien: true
          })
        }
      }
    })
  },
  getvoucher(e) {
    let that = this;
    let url = 'index.php?act=member_voucher&op=voucher_freeex';
    mph.postRequest(url, { tid: e.currentTarget.dataset.tid },
      (res) => {
        if (res.data.code == 200) {
          mph.showSuccess('领取成功');
          that.setData({
            btn_hide_blien: true
          })
          wx.setStorageSync('btn_hide_blien', true);
          that.hideModal()
        }
      })
  }, 
  /** 第8个模块的选项卡 */
  home8_sle:function(e){
    let num = e.currentTarget.dataset.id;
    let v = this.data.temp_val;
    v.home8_sel = num
    //点击切换选项卡
    this.setData({
      temp_val:v
    })
    //切换商品内容

    let o = e.currentTarget.dataset.obj;
    this.get_goods_list(o.data);
  },
  /***  切换商品内容 */
  get_goods_list:function(id) {//商品列表
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=goods&op=goods_list&gc_id=" + id +"&page=4",
      dataType: 'json',
      success: function (result) {
        if (result.statusCode == 200) {
          wx.hideLoading()
          let v = that.data.temp_val;
          v.goods_list = result.data.datas.goods_list;
          that.setData({
            temp_val: v,
          })
        }
      }
    })
  },
  btn_hide() {
    this.setData({
      btn_hide_blien: true
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let num = wx.getStorageSync('total_limit_num');

    this.get_cart_num();
    if (num) {
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + num	//显示的内容
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }
  },
  /*** 选项卡导航跳转 */
  switchTabT:function(e){
      app.globalData.gc_id = e.currentTarget.dataset.gcid;
    wx.switchTab({
      url: '/pages/classification/classification', success(res) {
        let page = getCurrentPages().pop();
        if (page == undefined || page == null) {
          return
        }
        page.onLoad();
      }
    })
  },
  onHide: function () {
    this.data.resnum = 0;
  },
  //https://test.mvip100.com/mobile/index.php?act=other&op=share_tips
  //搜索框背景提示文字
  share_tips: function () {
    let that = this;
    mph.postRequest('index.php?act=other&op=share_tips', {}, function (res) {
      if (res.data.code == 200) {
        wx.setStorageSync('share_tips_list', res.data.datas)
        that.setData({
          sousuoT: res.data.datas
        })
      }
    })
  }, 
  /*** 定位 */
  getcity: function () {
    var that = this;
    // 实例化API核心类
    var qqmapsdk = new QQMapWX({
      key: 'EDJBZ-GWDHP-E7FDG-LEPFJ-H5OXZ-AYBX6' // 必填
    });

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        // 调用接口
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            wx.setStorage({ key: 'currentLocation', data: res['result']['address_component']['city'] });
            that.setData({
              city: res['result']['address_component']['city']
            })
          },
          fail: function (res) {
          }
        })
      }
    })
  },
  imageLoad(e){
    var query = wx.createSelectorQuery();
    //选择id
    var that = this;
    var v = that.data.temp_val;
    var h6width = wx.getSystemInfoSync().windowWidth;
    // query.select('.home6 .item').boundingClientRect(function (rect) {
    v.h6height = v.h6width = (h6width * 0.15) + 'px'
    v.h8height = v.h8width = (h6width /5) + 'px'
      that.setData({
        temp_val: v
      })
    // }).exec();
  }

})


